// 主列表、编辑、尾部集合构成
import React, { useState, useEffect, useRef, forwardRef } from 'react';
import { Card, Table, Row, Input, Button, message, Typography } from 'antd';
import TableInput from './components/TableInput';
import _ from 'lodash';
import styles from './index.less';
import PageEmpty from '@/components/PageEmpty';
import { handlerApprovalStatusColor } from '@/utils/publicFunction';
import {
  CONSTANT_TAB_KEY1, // 投资正式版
  CONSTANT_TAB_KEY2, // 调整版
  CONSTANT_TAB_KEY3, // 实际版
  CONSTANT_EMPTYMSG1, // loading
  CONSTANT_VERSIONSTATUS, //版本状态对应
  CHANGE_NUM_VALUE, // 保留三位小数
  FLOAT_MODULUS, //浮点系数
  monthKeys, //24个月字段名
  NUM_VALUE, // isNaN
  ADDITION, // 相加
} from './utils/constant';
const { Text } = Typography;

import { getAdjustmentEditData, insertEditData } from './utils/request';

const EditFooter = props => {
  const { parentColumns, parentData, unitSize } = props;
  const [columns, setColumns] = useState([]);
  // 同步横向滚动
  const scroll = () => {
    const tableBody = document.querySelectorAll('.ant-table-body');
    if (tableBody[1]) {
      tableBody[1].style.overflow = 'hidden';
      tableBody[0].onscroll = () => {
        tableBody[1].scrollLeft = tableBody[0].scrollLeft;
      };
    }
  };

  // 滚动 初始化 keys columns data
  useEffect(() => {
    scroll();
    const columns = parentColumns.map((tar, index) => {
      if (index === 0) {
        return { ...tar, key: `footer_${tar.key}`, ellipsis: true };
      }
      return {
        ...tar,
        key: `footer_${tar.key}`,
        ellipsis: true,
        render: text => (
          <div className={Number(text) === 100 ? '' : 'colorRed'}>{text.toFixed(3)}%</div>
        ),
      };
    });
    setColumns(columns);
  }, []);

  return (
    <Table
      columns={columns}
      dataSource={parentData}
      style={{ paddingRight: 4 }}
      size="small"
      rowClassName={() => 'editable-row'}
      className={styles.footerTable}
      showHeader={false}
      pagination={false}
      scroll={{ x: parentColumns.length * unitSize + unitSize }}
    />
  );
};

const EditInput = props => {
  const {
    recordData: { text, record, index },
    dataIndex,
    num,
    insertData,
  } = props;

  const [val, setVal] = useState(text);
  const change = ({ target: { value } }) => {
    let newVal = CHANGE_NUM_VALUE(value);
    if (newVal === false) return;
    insertData(dataIndex, newVal, val, num - 1, index);
    setVal(newVal);
  };
  return (
    <Input
      className={styles['editable-cell-value-input']}
      onChange={change}
      value={val}
      suffix={'%'}
    />
  );
};

const Editable = props => {
  const {
    version: { id, versionNum, versionState },
    close,
  } = props;
  const [state, setState] = useState({
    data: [],
    columns: [],
    rawData: [], //原始数据
  });
  const [tableData, setTableData] = useState([]);
  const [tableColumn, setTableColumn] = useState([]);
  const [footerSum, setFooterSum] = useState(null);
  const [loading, setLoading] = useState(true);
  const [subLoading, setSubLoading] = useState(false);

  // 获取数据
  useEffect(() => {
    getData(id);
  }, []);

  // tableData 生成后创建 tableColumn
  useEffect(() => {
    if (state.columns.length === 0) return;
    scroll();
    setTableColumn(
      state.columns.map((col, num) => {
        if (!col.editable) {
          return col;
        }
        const attr = { dataIndex: col.dataIndex, num, insertData };
        return {
          ...col,
          render: (text, record, index) => (
            <EditInput recordData={{ text, record, index }} {...attr} />
          ),
        };
      }),
    );
  }, [state.columns]);

  // 接口拉取数据
  const getData = async versionId => {
    const res = await getAdjustmentEditData(versionId);
    const { columns, data, footerData } = res;
    setTableData(data);
    setFooterSum(footerData);
    setState(res);
    setLoading(false);
  };

  // 拿到的数据（newVal， val）都是原始数据，需要做验证
  const insertData = (dataIndex, newVal, val, productNum, monthNum) => {
    const diff = ADDITION(newVal, -val);
    console.log(
      `字段名=`,
      dataIndex,
      '\n',
      `两次输入差值=`,
      diff,
      '\n',
      `业态下标=`,
      productNum,
      '\n',
      `月份下标=`,
      monthNum,
    );
    footerSum[dataIndex] = ADDITION(footerSum[dataIndex], diff);
    setFooterSum({ ...footerSum });
    state.rawData[productNum][monthKeys[monthNum]] = (NUM_VALUE(newVal) / 100).toFixed(
      FLOAT_MODULUS + 2,
    );
    setState({ ...state, rawData: [...state.rawData] });
    console.log(`合计=`, footerSum);
    console.log(`总数据=`, state.rawData);
  };

  // 提交（存在非 100% 业态拒绝提交）
  const submit = async () => {
    setSubLoading(true);
    const index = Object.values(footerSum).findIndex(tar => {
      return Number(tar) !== 100;
    });
    if (index !== -1) {
      message.warning('存在业态回款系数合计不是100%，不允许保存');
      setSubLoading(false);
      return;
    }
    const res = await insertEditData(state.rawData, () => {
      message.success('保存成功');
      close();
    });
    setSubLoading(false);
  };

  return (
    <>
      {loading ? (
        <PageEmpty emptyTitle={CONSTANT_EMPTYMSG1} />
      ) : (
        <>
          <Row style={{ marginBottom: 10 }}>
            <Text>调整版{versionNum}&emsp;</Text>
            <Text className="version-status" strong>
              <i
                className="dots"
                style={{
                  background: handlerApprovalStatusColor(versionState),
                }}
              />
              {CONSTANT_VERSIONSTATUS[versionState]}
            </Text>
          </Row>
          <Table
            className={styles.PayBackModulus}
            columns={tableColumn}
            dataSource={tableData}
            rowClassName={() => 'editable-row'}
            size="middle"
            bordered
            pagination={false}
            scroll={{ x: tableColumn.length * 100 + 100, y: 'calc(100vh - 260px)' }}
            footer={() =>
              tableColumn.length > 0 && (
                <EditFooter
                  unitSize={100}
                  parentColumns={tableColumn}
                  parentData={[footerSum]}
                  className={'ant-table-fixed'}
                />
              )
            }
          ></Table>
          <Row style={{ margin: 10, textAlign: 'center' }}>
            <Button
              loading={subLoading}
              onClick={submit}
              type="primary"
              style={{ marginRight: 10 }}
            >
              保存
            </Button>
            <Button onClick={close}>取消</Button>
          </Row>
        </>
      )}
    </>
  );
};

export default Editable;
